package com.learning.spring.security.base.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.core.Authentication;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: Expressions
 * Description:
 * Date: 2022/7/11 14:39
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class ExpressionsConfiguration {

    /**
     * 在此配置中，匹配的url将传入路径变量(并将其转换为checkUserId方法)。
     * 例如，如果URL是 /user/123/resource，那么传入的 id 将是 123
     *
     * @param http
     * @return
     * @throws Exception
     */
    /*@Bean
    SecurityFilterChain web(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .antMatchers("/user/**").access("@webSecurity.check(authentication,request)")
                        .antMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)")
                );
        return http.build();
    }*/

    @Bean
    public WebSecurity webSecurity() {
        return new WebSecurity();
    }

    /**
     * 自定义表达式类
     */
    public static class WebSecurity {

        /**
         * 表达式方法
         *
         * @param authentication
         * @param request
         * @return
         */
        public boolean check(Authentication authentication, HttpServletRequest request) {
            return true;
        }

        /**
         * 表达式方法，Web 安全表达式中的路径变量
         *
         * @param authentication
         * @param id
         * @return
         */
        public boolean checkUserId(Authentication authentication, int id) {
            return true;
        }
    }
}
